<template>
  <div class="view-fill">
    <div class="app-container-flex">
      <full-screen
        v-model="showDialog"
        :title="title"
        @returnBack="$emit('returnModify')"
      >
        <template v-slot:full-button>
          <el-button :disabled="!canSave" @click="save()">保存</el-button>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :disabled="formInfo.disabled"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
            >
              <template v-slot:form-depotName>
                <el-input
                  v-model="formInfo.data.depotName"
                  class="not-mongolia"
                  type="input"
                  :required="true"
                  :disabled="true"
                  placeholder="请选择出库仓库"
                >
                  <template #append>
                    <el-icon @click="selectExportDepot"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-storeDepotName>
                <el-input
                  v-model="formInfo.data.storeDepotName"
                  class="not-mongolia"
                  type="input"
                  :required="true"
                  :disabled="true"
                  placeholder="请选择入库仓库"
                >
                  <template #append>
                    <el-icon @click="selectStoreDepot"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
            </page-form>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')" />
          </div>
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <page-filter :filter-list="filterInfo.list">
              <template v-slot:filter-addProduct>
                <el-button :disabled="!canAddProduct" @click="addProduct"
                  >添加产品</el-button
                >
              </template>
              <template v-slot:filter-removeProduct>
                <el-button
                  :disabled="!canRemoveProduct"
                  @click="removeProduct()"
                  >删除产品</el-button
                >
              </template>
            </page-filter>
            <div class="flex_full_item">
              <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
                <!-- 表格 -->
                <page-table
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :summary="true"
                  :summary-field-list="tableInfo.summaryFieldList"
                  :tab-index="true"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :row-class-name="tableRowClassName"
                  :isDynamic="true"
                  @handleEvent="handleEvent"
                >
                  <template v-slot:col-qty="scope">
                    <el-form-item class="margin-bottom">
                      <div class="page-table-input-number-wrapper">
                        <div class="page-table-input-number-left">
                          <div class="page-table-input-number-item">
                            <el-form-item
                              :prop="`data.${scope.$index}.largeUnitQty`"
                              :rules="
                                scope.$index >= 0
                                  ? [
                                      {
                                        validator: $validate.positiveAndZero,
                                        trigger: 'blur',
                                      },
                                    ]
                                  : []
                              "
                            >
                              <el-input-number
                                v-model.lazy="scope.row.largeUnitQty"
                                style="width: 100%; margintop: 18px"
                                clearable
                                controls-position="right"
                                :precision="
                                  scope.row.qtyOperateMode === 0 ||
                                  scope.row.qtyOperateMode === 2
                                    ? 0
                                    : systemConfig.qty_show_precision
                                "
                                :min="0"
                                :max="largeMax(scope.row)"
                                @change="
                                  changeLarge(
                                    $event,
                                    scope.row,
                                    `data.${scope.$index}.largeUnitQty`
                                  )
                                "
                              />
                            </el-form-item>
                            <div class="page-table-input-number-item-unite">
                              {{ scope.row.unitName }}
                            </div>
                          </div>
                          <div
                            v-if="
                              scope.row.unitConvertCoefficient > 1 &&
                              scope.row.qtyOperateMode === 2
                            "
                            class="page-table-input-number-item"
                          >
                            <el-form-item>
                              <el-input-number
                                v-model.lazy="scope.row.smallUnitQty"
                                style="width: 100%; margintop: 18px"
                                clearable
                                controls-position="right"
                                :precision="0"
                                :min="0"
                                :max="smallMax(scope.row)"
                              />
                            </el-form-item>
                            <div class="page-table-input-number-item-unite">
                              {{ scope.row.calcUnitName }}
                            </div>
                          </div>
                        </div>
                        <div
                          v-if="scope.row.qtyOperateMode === 2"
                          class="page-table-input-number-right"
                        >
                          {{ $fn.qtyFormatter(scope.row.qty) }}
                        </div>
                      </div>
                    </el-form-item>
                  </template>
                </page-table>
              </el-form>
            </div>
          </div>
        </div>
      </full-screen>
    </div>
    <select-depot
      v-if="selectDepotInfo.visible"
      v-model:show-dialog="selectDepotInfo.visible"
      :check-box="false"
      :query="selectDepotInfo.query"
      :highlight-row="true"
      :check-lock="true"
      :save-empty="true"
      @callback="selectDepotCallBack"
    />
    <select-depot
      v-if="selectStoreDepotInfo.visible"
      v-model:show-dialog="selectStoreDepotInfo.visible"
      :check-box="false"
      :query="selectStoreDepotInfo.query"
      :highlight-row="true"
      :check-lock="true"
      :save-empty="true"
      @callback="selectStoreDepotCallBack"
    />

    <select-group-stock
      v-if="selectDepotStorageInfo.visible"
      v-model:show-dialog="selectDepotStorageInfo.visible"
      :query="selectDepotStorageInfo.query.queryMap"
      :exclude-query-list="selectDepotStorageInfo.excludeQueryList"
      :api="selectDepotStorageInfo.api"
      :table-key="selectDepotStorageInfo.tableKey"
      :show-price="$permission('wmsAccountExportOrder:price')"
      @callback="selectDepotStorageCallBack"
    />
  </div>
</template>

<script setup name="wmsExportStockOrderModify">
import { getBeginningDepotStockPage } from '@/api/beginning'
import SelectGroupStock from '@/components/SelectGroupStock/index'
import { getCoreSystemConfigAll } from '@/api/core'
import {
  getWmsExportStockById,
  createWmsExportStock,
  updateWmsExportStock,
  getWmsExportStockDetailCustomizeListAll,
} from '@/api/wms'
import { getCustomizeSetting } from '@/api/customize'
import moment from 'moment'

const emits = defineEmits()
const { proxy } = getCurrentInstance()
const props = defineProps(['visible', 'title', 'exportId'])

const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const formRefs = ref('')
//表单相关
const formInfo = ref({
  ref: null,
  data: {
    depotName: '',
    depotId: '',
    deptName: '',
    deptId: '',
    storeDepotName: '',
    storeDepotId: '',
    storeDeptName: '',
    storeDeptId: '',
    phone: '',
    type: '3',
  },
  fieldList: [
    {
      label: '出库仓库',
      value: 'depotName',
      type: 'slot',
    },
    {
      label: '出库部门',
      value: 'deptName',
      type: 'input',
      disabled: true,
    },
    {
      label: '入库仓库',
      value: 'storeDepotName',
      type: 'slot',
      show: false,
    },
    {
      label: '入库部门',
      value: 'storeDeptName',
      type: 'input',
      show: false,
      disabled: true,
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
      className: 'not-br',
      maxlength: 200,
    },
  ],
  rules: {
    depotName: [
      { required: true, message: '请选择出库仓库', trigger: 'change' },
    ],
    storeDepotName: [
      { required: true, message: '请选择入库仓库', trigger: 'change' },
    ],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {},
  },
  list: [
    { type: 'slot', value: 'addProduct' },
    { type: 'slot', value: 'removeProduct' },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  map: new Map(),
  isSysGroup: true, //新增修改页是否有后端合并
  sysGroup: [], //新增修改页后端合并项
  selections: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'price', show: 'false' },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '删除',
        event: removeProduct,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
      },
    ],
  },
})
const selectDepotInfo = ref({
  visible: false,
  query: {
    depotAuth: 'id',
    status: 1,
    useTypeId: 1,
    isCargoSpaceManage: 1,
    idNot: '',
  },
})
const selectStoreDepotInfo = ref({
  visible: false,
  query: {
    depotAuth: 'id',
    status: 1,
    useTypeId: 1,
    idNot: '',
  },
})
const selectDepotStorageInfo = ref({
  //库存产品
  visible: false,
  api: getBeginningDepotStockPage,
  tableKey:
    'productPageWithWmsAccountExportStock-com.slip.spd.entity.vo.beginning.BeginningDepotStockVO',
  excludeQueryList: [], //库存产品过滤配置
  query: {
    queryMap: {
      depotId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      generalProductCategory: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 0,
      },
    },
    queryParams: {},
  },
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})

const canSave = computed(() => {
  return tableInfo.value.data.length
})
const canAddProduct = computed(() => {
  return formInfo.value.data.depotId && formInfo.value.data.deptId
})
const canRemoveProduct = computed(() => {
  return tableInfo.value.selections.length
})
watch(
  () => tableInfo.value.data,
  (val) => {
    if (val.length) {
      val.forEach((row) => {
        let smallUnitQty = parseFloat(row.smallUnitQty || 0)
        let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
        let largeUnitQty = parseFloat(row.largeUnitQty || 0)
        let calcQty = proxy.$fn.accAdd(
          proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
          smallUnitQty
        )
        let qty = proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
        row['calcQty'] = calcQty
        row['qty'] = qty
        row.sumAmount = proxy.$fn.accDiv(
          proxy.$fn.accMul(calcQty, parseFloat(row.price)),
          unitConvertCoefficient
        )
        if (row.details && row.details.length) {
          row.details[0].qty = qty
          row.details[0].calcQty = calcQty
          row.details[0].largeUnitQty = largeUnitQty
          row.details[0].smallUnitQty = smallUnitQty
          row.details[0].sumAmount = row.sumAmount
        }
      })
    }
  },
  {
    deep: true,
  }
)

watch(
  () => formInfo.value.data.type,
  (val) => {
    showFieldListItem(val == 2, 'storeDeptName')
    showFieldListItem(val == 2, 'storeDepotName')
  }
)

let obj = {
  qty: {
    label: '数量',
    value: 'qty',
    type: 'slot',
    minWidth: '250px',
  },
  price: {
    label: '单价',
    value: 'price',
    minWidth: '150px',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('wmsAccountExportOrder:price'),
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('wmsAccountExportOrder:price'),
    hidden: true,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    permission: !proxy.$permission('wmsAccountExportOrder:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
  },
}
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})
getCustomize()

onMounted(() => {
  formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
  proxy.$nextTick(() => {
    if (!props.exportId) {
      formInfo.value.fieldList = formInfo.value.fieldList.filter(
        (item) => item.value !== 'orderNo'
      )
    }
  })
})

function onlyShowOption() {
  let options = proxy.$store.state.permission.dict['wms_export_type'] || []
  if (options.length) {
    options = options.filter((item) => item.code == 2).map((item) => item.code)
  }
  return options
}
function showFieldListItem(show, nameValue) {
  console.log(show, nameValue)
  let fieldList = formInfo.value.fieldList
  fieldList.forEach((item) => {
    if (nameValue === item.value) {
      item.show = show
    }
  })
}
function largeMax(row) {
  if (row.qtyOperateMode === 2) {
    return parseInt(row.stockAvailableCalcQty / row.unitConvertCoefficient)
  } else {
    return row.stockAvailableQty
  }
}
function smallMax(row) {
  let largeUnitQty = parseInt(
    row.stockAvailableCalcQty / row.unitConvertCoefficient
  )
  if (largeUnitQty === 0 || row.largeUnitQty === largeUnitQty) {
    return parseInt(row.stockAvailableCalcQty % row.unitConvertCoefficient)
  } else {
    return row.unitConvertCoefficient - 1
  }
}
function changeLarge(e, row, str) {
  proxy.$refs.tableForm.clearValidate(str)
  let largeUnitQty = parseInt(
    row.stockAvailableCalcQty / row.unitConvertCoefficient
  )
  if (row.qtyOperateMode === 2 && row.unitConvertCoefficient > 1) {
    if (largeUnitQty > 0 && e === largeUnitQty) {
      let smallUnitQty = parseInt(
        row.stockAvailableCalcQty % row.unitConvertCoefficient
      )
      if (row.smallUnitQty > smallUnitQty) {
        row.smallUnitQty = smallUnitQty
      }
    }
  }
}
function tableRowClassName({ row = undefined }) {
  if (row.isChoice) {
    return 'success-row'
  } else {
    return ''
  }
}
function ifRenderValue() {
  return tableInfo.value.isSysGroup
}

function getMain() {
  getWmsExportStockById(props.exportId).then((resp) => {
    if (resp && resp.success) {
      formInfo.value.data = resp.data
    }
  })
  filterInfo.value.query.queryMap.orderId.value = props.exportId
  getList()
}

function getList() {
  //修改请求明细信息
  getWmsExportStockDetailCustomizeListAll(filterInfo.value.query).then(
    (resp) => {
      if (resp && resp.success && resp.data.length) {
        let data = resp.data
        data.forEach((item) => {
          //将返回的数据变成Map形式
          let key = []
          tableInfo.value.sysGroup.forEach((row) => {
            let obj = {}
            obj.columnName = row.columnName
            obj.asTbName = row.asTbName
            obj.value = item[row.key]
            key.push(obj)
          })
          item.key = JSON.stringify(key)
          tableInfo.value.map.set(item.key, item)
        })
        tableInfo.value.data = data
      }
    }
  )
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function save() {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    const newDetails = tableInfo.value.data.filter(
      (row) => row.productId && row.qty
    )
    if (!newDetails.length) {
      proxy.$message({
        message: '请添加有效的产品',
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
      return
    }
    let details = proxy.$fn.filterBlacklist(newDetails)
    //校验过期产品是否准许出库
    getCoreSystemConfigAll().then((resp) => {
      if (resp && resp.success) {
        let find = resp.data.find(
          (item) => item.systemConfigCode === 'allow_expire_out'
        )
        if (find) {
          let expire = validateExpire(newDetails)
          if (find.value === '1') {
            if (expire) {
              proxy
                .$confirm(expire + ',是否继续?', '警告', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  dangerouslyUseHTMLString: true,
                })
                .then(() => {
                  const data = formInfo.value.data
                  data.mergeDetails = details
                  const api = data.id
                    ? updateWmsExportStock
                    : createWmsExportStock
                  api(data).then((resp) => {
                    if (resp && resp.success) {
                      showDialog.value = false
                      emits('returnModify', false)
                    }
                  })
                  return
                })
                .catch(() => {
                  return
                })
            } else {
              const data = formInfo.value.data
              data.mergeDetails = details
              const api = data.id ? updateWmsExportStock : createWmsExportStock
              api(data).then((resp) => {
                if (resp && resp.success) {
                  showDialog.value = false
                  emits('returnModify', false)
                }
              })
            }
          } else {
            if (expire) {
              proxy.$alert(expire + '，不允许出库！', '操作提示', {
                confirmButtonText: '确定',
                dangerouslyUseHTMLString: true,
              })
              return
            } else {
              const data = formInfo.value.data
              data.mergeDetails = details
              const api = data.id ? updateWmsExportStock : createWmsExportStock
              api(data).then((resp) => {
                if (resp && resp.success) {
                  showDialog.value = false
                  emits('returnModify', false)
                }
              })
            }
          }
        } else {
          const data = formInfo.value.data
          data.mergeDetails = details
          const api = data.id ? updateWmsExportStock : createWmsExportStock
          api(data).then((resp) => {
            if (resp && resp.success) {
              showDialog.value = false
              emits('returnModify', false)
            }
          })
        }
      }
    })
  })
}
function validateExpire(list = []) {
  let currentDate = moment().format('YYYY-MM-DD')
  let msg = ''
  console.log(list)
  list.forEach((item, index) => {
    if (item.validityDate && moment(item.validityDate).isBefore(currentDate)) {
      msg = msg + `第【${index + 1}】行产品【${item.commonName}】已过期，<br>`
    }
  })
  return msg
}
//选择出库仓库
function selectExportDepot() {
  selectDepotInfo.value.visible = true
  selectDepotInfo.value.query.idNot = formInfo.value.data.storeDepotId
}
function selectDepotCallBack(data = undefined) {
  if (data && data.id) {
    formInfo.value.data.depotId = data.id
    formInfo.value.data.depotName = data.name
    formInfo.value.data.deptName = data.deptName || ''
    formInfo.value.data.deptId = data.deptId || ''
    tableInfo.value.data = []
    tableInfo.value.map = new Map()
    selectDepotStorageInfo.value.excludeQueryList = []
  } else {
    formInfo.value.data.depotId = ''
    formInfo.value.data.depotName = ''
    formInfo.value.data.deptName = ''
    formInfo.value.data.deptId = ''
    tableInfo.value.data = []
    tableInfo.value.map = new Map()
    selectDepotStorageInfo.value.excludeQueryList = []
  }
}
//选择出库仓库
function selectStoreDepot() {
  selectStoreDepotInfo.value.visible = true
  selectStoreDepotInfo.value.query.idNot = formInfo.value.data.depotId
}
function selectStoreDepotCallBack(data = undefined) {
  if (data && data.id) {
    formInfo.value.data.storeDepotId = data.id
    formInfo.value.data.storeDepotName = data.name
    formInfo.value.data.storeDeptName = data.deptName || ''
    formInfo.value.data.storeDeptId = data.deptId || ''
  } else {
    formInfo.value.data.storeDepotId = ''
    formInfo.value.data.storeDepotName = ''
    formInfo.value.data.storeDeptName = ''
    formInfo.value.data.storeDeptId = ''
  }
}
//选择库存产品
function addProduct() {
  let keys = [...tableInfo.value.map.keys()]
  let excludeQueryList = []
  if (keys.length && tableInfo.value.sysGroup.length) {
    excludeQueryList = keys.map((item) => JSON.parse(item))
  }
  selectDepotStorageInfo.value.excludeQueryList = excludeQueryList //库存产品过滤配置
  selectDepotStorageInfo.value.query.queryMap.depotId.value =
    formInfo.value.data.depotId
  selectDepotStorageInfo.value.visible = true
}
function selectDepotStorageCallBack(rows) {
  if (rows.length) {
    rows.forEach((item) => {
      //将返回的数据变成Map形式
      let key = []
      tableInfo.value.sysGroup.forEach((row) => {
        let obj = {}
        obj.columnName = row.columnName
        obj.asTbName = row.asTbName
        obj.value = item[row.key]
        key.push(obj)
      })
      item.key = JSON.stringify(key)
      tableInfo.value.map.set(item.key, item)
    })

    tableInfo.value.data = rows.concat(tableInfo.value.data)
  }
}
//删除产品
function removeProduct(selectRow = undefined) {
  if (selectRow && selectRow.productId) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (row) => row !== selectRow
    )
    let key = selectRow.key
    tableInfo.value.map.delete(key)
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.value.selections.forEach((row) => {
          for (let [key, value] of tableInfo.value.map) {
            if (key === row.key) {
              tableInfo.value.map.delete(key)
            }
          }
        })
        tableInfo.value.data = tableInfo.value.data.filter(
          (row) => !tableInfo.value.selections.includes(row)
        )
      })
  }
}
function getCustomize() {
  let param = {
    tableKey:
      'wmsExportStockDetailModify-com.slip.spd.entity.vo.wms.WmsExportStockDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      filterInfo.value.query.customizeUserVO = data

      let arr = [
        {
          columnName: '`batch_number`',
          asTbName: 'beginning_depot_stock',
          key: 'batchNumber',
        },
        {
          columnName: '`supplier_id`',
          asTbName: 'beginning_depot_stock',
          key: 'supplierId',
        },
        {
          columnName: '`production_date`',
          asTbName: 'beginning_depot_stock',
          key: 'productionDate',
        },
        {
          columnName: '`validity_date`',
          asTbName: 'beginning_depot_stock',
          key: 'validityDate',
        },
        {
          columnName: '`price`',
          asTbName: 'beginning_depot_stock',
          key: 'price',
        },
        {
          columnName: '`product_id`',
          asTbName: 'beginning_depot_stock',
          key: 'productId',
        },
      ]
      tableInfo.value.sysGroup = arr
      if (props.exportId) {
        getMain()
      }
    }
  })
}
</script>

<style scoped lang="scss">
:deep(.page-table > .el-table) {
  overflow: hidden;
}
</style>
